;(function () {
  new Vue({
    el: '#createCm',
    data: {
		lsListData: [],
		lsSelectData: [],
      type: [{name: '公司', type: 'QY'}, {name: '个人', type: 'PE'}],
      typeAct: 'QY',
      blacklist: [{name: '是', type: 'Y'}, {name: '否', type: 'N'}],
      blacklistAct: 'N',
      industryData: [],
      selectedIndustry:[],
      customerStateData: [
      ],
      selectedCustomerState:[],
      channelTypeData: [],
      selectedChannelType:[],
      channelNameData: [],
      selectedChannelName: [],
      selectedChannelNameVal:[],
      processData: [],
      selectedProcess:[],
      fieldData:[],
      //input v-model
      customerData: {cincbInfo:{logoUrl:''}},
      followupData: [],
      selectedFollowType: [],
      followupmemo: '',
      planfollowupcontent: '',
      //红色框框警告
      cmflag: false,
      cmstatusflag: false,
      industryflag: false,
      lspeopleflag: false,
      lsphoneflag: false,
      qdflag: false,
      qdnmflag: false,
      id: hlUrlUtil.GetQueryString('id'),
      h0: '',
      h1: '',
      m0: '',
      m1: '',
      followTime:'',
      planfollowuptime:'',
			//
			tmpData: [],
			resData: []
    },
    filters: {
      customerState (val) {
        let result;
        switch (val) {
          case 'PO':
            result = '潜在客户'
            break;
          case 'YX':
            result = '意向客户'
            break;
          case 'LS':
            result = '流失客户'
            break;
			case 'ZD':
			  result = '重点客户'
			  break;
          case 'CJ':
            result = '成交客户'
            break;
          case 'BL':
            result = '黑名单客户'
            break;
          default:
            result = '--'
        }
        return result
      }
    },
    methods: {
		getLsReason() {
		  var that = this
		  hlhttp.get({
		    url: 'configure/dict',
		    data: {
		      module_code: 'ZHSH',
		      config_name: 'ZS_LOSS_REASON'
		    },
		    success: function (data) {	
				var temp = data.filter((item) => {return item.status == 'Y'})
		      that.lsListData = hlArrayUtil.replaceData(temp, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
		    },
		  })
		},
			ZS_CUSTOMER_STATUS() {
			    var self = this
			    hlhttp.get({
			        url: 'configure/dict',
			        data: { module_code: 'ZHSH', config_name: 'ZS_CUSTOMER_STATUS' },
			        success: data => {								
			            self.customerStateData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
			        }
			    })
			},
      getIndustryData () {
        var self = this
        hlhttp.get({
          url: 'configure/industry/dict',
          success: data => {
            self.industryData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      getChannelTypeData () {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH', config_name: 'ZS_CHANNEL_CATE'},
          success: data => {
            self.channelTypeData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      getChannelNameData () {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH', config_name: 'ZS_CHANNEL_NAME'},
          success: data => {
            self.channelNameData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      getProcessData () {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH', config_name: 'ZS_PROCESS_MANAGER'},
          success: data => {
            self.processData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      // 检测自定义字段填写是否符合要求
      checkCustom() {
        let flag = true
        this.resData.map(item => {
        	if (item.requiredFlag == 'Y' && (!item.value || !item.value.length) && item.type != 'line') {
        	  flag = false
        	}
        })	
        return flag
      },
      postCm () {
        this.cmflag = false;
        this.cmstatusflag = false;
        this.industryflag = false;
        this.lspeopleflag = false;
        this.lsphoneflag = false;
        this.qdflag = false;
        this.qdnmflag = false;

        if (!this.customerData.type) {
          this.cmflag = true;
          hl.toast('请填写客户名称')
          return
        }
        if (!this.customerData.customerState) {
          hl.toast('请选择客户状态')
          return
        }
        if (!this.customerData.lperson) {
          hl.toast('请填写联系人')
          return
        }
        if (!this.customerData.phone) {
          hl.toast('请填写联系电话')
          return
        }
        if (!this.h0 || !this.m0) {
          hl.toast('跟进时间为必填')
          return
        }
        if (this.h0) {
          if (isNaN(this.h0)) {
            hl.toast('小时不是数字')
            return
          }
        }
        if (this.m0) {
          if (isNaN(this.m0)) {
            hl.toast('分钟不是数字')
            return
          }
        }
        if (this.h0 > 23 || this.h0 < 0) {
          hl.toast('小时不能大于23或者小于0')
          return
        }
        if (this.m0 > 59 || this.m0 < 0) {
          hl.toast('分钟不能大于59或者小于0')
          return
        }
        if (this.h1) {
          if (isNaN(this.h1)) {
            hl.toast('小时不是数字')
            return
          }
          if (this.h1 > 23 || this.h1 < 0) {
            hl.toast('小时不能大于23或者小于0')
            return
          }
        }
        if (this.m1) {
          if (isNaN(this.m1)) {
            hl.toast('分钟不是数字')
            return
          }
          if (this.m1 > 59 || this.m1 < 0) {
            hl.toast('分钟不能大于59或者小于0')
            return
          }
        }

        if(!this.checkCustom()){
          hl.toast('请选择自定义选项')
          return
        }

        var cus_info = {
          type: this.customerData.type,
          name: this.customerData.name,
          industry: this.selectedIndustry.length ? this.selectedIndustry.join() : '#',
          lperson: this.customerData.lperson,
          phone: this.customerData.phone,
          channel_name: this.selectedChannelName.length ? this.selectedChannelName.join() : '#',
          channel_type: this.selectedChannelType.length ? this.selectedChannelType.join() : '#',
          customer_state: this.selectedCustomerState.length ? this.selectedCustomerState.join() : '#',
          memo: this.customerData.memo,
          black_state: this.customerData.blackState,
          idcode: this.customerData.idcode,
          email: this.customerData.email,
          short_name: this.customerData.shortName,
          process_type: this.selectedProcess.length ? this.selectedProcess.join() : '#',
          address: this.customerData.address,
          zipcode: this.customerData.zipcode,
          custom_config_property: JSON.stringify(this.newFieldsData()),
					
					loss_reason: this.lsSelectData && this.lsSelectData.length ? this.lsSelectData[0] : '#'
        };

        var timer1, timer2;
        if (this.followTime) {
          timer1 = this.followTime +' '+this.h0+':'+this.m0+':00'
        }
        if (this.planfollowuptime) {
          timer2 = this.planfollowuptime +' '+(this.h1 || '0')+':'+(this.m1 || '0')+':00'
        }
        var followup_info = {
          "followup_time": timer1,
          "followup_type": this.selectedFollowType.length ? this.selectedFollowType.join() : '#',
          "followup_memo": this.followupmemo,
          "plan_followup_time": timer2,
          "plan_followup_content": this.planfollowupcontent
        };
        var data = {
          id: this.id || '975',
          cus_info: JSON.stringify(cus_info),
          followup_info: JSON.stringify(followup_info),
		  page_customize_component_biz_content: JSON.stringify(this.newFieldsData()),
        }

        hlhttp.put({
          url: 'customer/_followup',
          data,
          success: () => {
            hl.toast('编辑成功')
            hlUrlUtil.goTo('customerDetails', {id: this.id, ddtab:true, page: 'customerManagement', event: 'follow'})
          }
        })
      },
      backToLastPage(){
        hlUrlUtil.goTo('customerDetails', {id: this.id, ddtab:true, page: 'customerManagement'})
      },
      //自定义字段获取
      marketCustomizeDt (val) {
        var that =this
      	hlhttp.get({
      		url: 'configure/customize_column',
      		data: {
      		  module: 'ZHSH',
      		  config_name: 'ZS_CUSTOMIZE_COLUMNS',
      		},
      		success: (res) => {
            let arr = [...res.customizeColumns, ...res.systemColumns]
            for (var i = arr.length - 1; i >= 0; i--) {
              if (arr[i].isValid == 'false') {
                arr.splice(i,1)
              }
            }//去除多余数据（未启动，无关联）
            console.log(arr)
            // if(val){
            //   arr = hlArrayUtil.removeRepeat([...val,...arr], 'configCode');
            // }

             //若有合同详情，则合并,去重（保留合同）
            let textList = []
            let noTextList = []
            arr.map((item,index) =>{
              if(item.fieldType == 'text'){
                textList.push(item)
              }else{
                noTextList.push(item)
              }
            })
            arr = [...noTextList,...textList]
            //重新排序，将文本类型放到最后
            console.log(arr)
            arr.map(item => {
              if(!item.select){
                if (item.fieldType == 'radio' || item.fieldType == 'checkbox' || item.fieldType == 'select') {
                  item.select = [];
                  item.selectArr = item.fieldRange.split(',')
                  item.selectArrCopy = []
                  item.selectArr.map(item0 => {
                    item.selectArrCopy.push({
                      name: item0,
                      code: item0
                    })
                  })
                } else {
                  item.select = '';
                }
              }
            })
            if(val){
              val.map(item =>{
                arr.map(single =>{
                  if(single.configCode == item.configCode){
                    single.select = item.select
                  }
                })
              })
            }
          that.fieldData = arr
      		}
      	})
      },
      // 新的自定义字段
      resMake (type, val) {
      	// text  textarea mobile email phone  time date  dateTime
      	let t0 = ['text', 'email', 'area', 'mobile', 'phone', 'time', 'date', 'dateTime', 'select', 'radio', 'checkbox'];						
      	let t1 = ['file'];
      	if (t0.indexOf(type) > -1) return val;
      	if (t1.indexOf(type) > -1) {
      		let data = []
      		if (val) {
      			val.map(item => {
      				data.push(item.response ? item.response : item)
      			})
      		}
      		return data
      	}
      },
      
      newFieldsData () {
      	let data = [];
      	this.resData.map(item => {
      		data.push({
      			component_code: item.code,
      			component_type: item.type,
      			property: this.resMake(item.type, item.value)
      		})
      	})
      	return data;
      },
      getcustomerInfo () {
        hlhttp.get({
          url: 'customer,cincb_info',
          data: { customer_id: this.id },
          success: res => {
            if (!res.cincbInfo) {
              res.cincbInfo = {}
            }
            if (res.cincbInfo) {
              if (!res.cincbInfo.logoUrl) {
                res.cincbInfo.logoUrl = '../../../assets/images/bg-01.png'
              }
            }
this.tmpData = res.pageCustomizeComponentBizContentList ? res.pageCustomizeComponentBizContentList : []
            this.customerData = res;
            if(res.customerState) this.selectedCustomerState.push(res.customerState)
            if(res.processType) this.selectedProcess.push(res.processType)
            if(res.industry) this.selectedIndustry.push(res.industry)
            if(res.channelCategoryCode) this.selectedChannelType.push(res.channelCategoryCode)
            if(res.channelNameCode) this.selectedChannelName.push(res.channelNameCode)
			if (res.lossReason) {this.lsSelectData.push(res.lossReason)}
            if(res.channelNameVal) this.selectedChannelNameVal.push(res.channelNameVal)
            // this.marketCustomizeDt(res.customConfigProperty ? JSON.parse(res.customConfigProperty) : [])
          }
        })
      },
      getFollowupData () {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH0SHJI', config_name: 'SJ_FOLLOWUP_TYPE'},
          success: data => {
            self.followupData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      handleChannelNameChange(data){
        this.selectedChannelNameVal = data[0]['code'].split()
      }
    },
    mounted () {
      this.getIndustryData()
      this.getChannelTypeData()
      this.getChannelNameData()
      this.getProcessData()
      this.getFollowupData()
      this.getcustomerInfo()
			this.ZS_CUSTOMER_STATUS()
			
			this.getLsReason()

    }
  })
} ())
